package com.ynny.Controller;


import com.ynny.dao.UserDao;
import com.ynny.entity.R;
import com.ynny.entity.User;
import com.ynny.entity.UsersDTO;
import com.ynny.service.UserServicelmpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserDao userDao;

    @Autowired
    UserServicelmpl userService;

    @GetMapping("/{id}")
    public R get(@PathVariable(name = "id") Integer id) {

        System.out.println("获取的id：" + id);

        User user = userDao.selectUserById(id);
        if (user == null) {
            new R(201, "查询无果", null);
        }

        return R.ok(user);
    }


    //查询所有用户信息
    @RequestMapping("/list")
    public R list() {

        //模拟集合数据
        List<User> users = userDao.selectAllUsers();

        return R.ok(users);

    }

    @PostMapping("/add")
    public R add(@RequestBody User user) {


        System.out.println("request:----》" + user);
        //添加用户 判断用户名是否存在
        //
//        userDao.selectUserByUserName();

//        int i = userDao.addUser(user);

//        int i = userService.saveUser(user);

//        if (i == 200 ){
//            return R.ok(user.getUsername());
//        } else if (i == 202) {
//            return new R(202,"用户名已经存在",null);
//        }
        return R.ok(null);
    }


    @DeleteMapping("/{id}")
    public R delete(@PathVariable(name = "id") Integer id) {

        System.out.println("删除的用户id:" + id);
        int i = userDao.deleteUser(id);

        return R.ok(null);

    }


    @PutMapping
    public R update(@RequestBody User user) {

        System.out.println("需要修改的用户为: " + user);

        int i = userDao.updateUser(user);

        if (i > 0) {
            return R.ok(user.getUsername());
        }

        return R.ok(null);

    }


    @PostMapping("/register")
    public R register(@RequestBody UsersDTO user) {

        //数据校验  -----》 非空校验 长度校验  格式校验  这些都是controller做的

        if (user.getUsername() == null || user.getPassword() == null) {
            return R.fail(201, "用户名或密码不能为空");
        }
        //注册是一个业务功能
        int res = userService.register(user);
        if (res == 200) {
            return R.ok(user);
        } else if (res == 211) {
            return R.fail(211, "用户名已存在");
        }

        return R.ok(null);
    }
}